from sqlalchemy import create_engine, text
from settings import settings
from database.database import engine
from models import user, ota

def create_database_if_not_exists():
    # 连接到 MySQL，不指定数据库
    engine_without_db = create_engine(settings.DB_URL_WITHOUT_DB, echo=False)

    # 检查数据库是否存在
    with engine_without_db.connect() as conn:
        result = conn.execute(text(f"SHOW DATABASES LIKE '{settings.MYSQL_DB}'"))
        if result.fetchone() is None:
            print(f"📦 数据库 '{settings.MYSQL_DB}' 不存在，正在创建...")
            conn.execute(text(f"CREATE DATABASE {settings.MYSQL_DB} CHARACTER SET utf8mb4"))
            print("✅ 数据库创建完成！")
        else:
            print(f"✅ 数据库 '{settings.MYSQL_DB}' 已存在。")

def create_tables():
    """创建所有表"""
    print("📦 正在创建数据库表...")
    # 导入所有模型以确保它们被注册
    from models.user import User
    from models.ota import OTAFirmware
    
    # 先删除旧表（如果存在）
    try:
        with engine.connect() as conn:
            conn.execute(text("DROP TABLE IF EXISTS ota_firmware"))
            conn.execute(text("DROP TABLE IF EXISTS users"))
            conn.commit()
            print("🗑️ 旧表删除完成")
    except Exception as e:
        print(f"⚠️ 删除旧表时出错: {e}")
    
    # 创建新表
    user.Base.metadata.create_all(bind=engine)
    ota.Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建完成！")

if __name__ == "__main__":
    create_database_if_not_exists()
    create_tables()
